//
//  RisacTextFieldView.swift
//  Risac
//
//  Created by remy on 2018/7/25.
//

import SnapKit

@objc public protocol RisacTextFieldViewDelegate: AnyObject {
    @objc optional func textFieldEditBegin(view: RisacTextFieldView, textField: UITextField)
    @objc optional func textFieldEditEnd(view: RisacTextFieldView, textField: UITextField)
    @objc optional func textFieldEditChanged(view: RisacTextFieldView, textField: UITextField)
    @objc optional func textFieldReturn(view: RisacTextFieldView, textField: UITextField)
}

open class RisacTextFieldView: UIView, ViewLinable {
    
    public let textField = UITextField()
    public weak var delegate: RisacTextFieldViewDelegate?
    public var contentInset: UIEdgeInsets = .zero {
        didSet { updateInset() }
    }
    public var text: String {
        get { return textField.text ?? "" }
        set { textField.text = newValue }
    }
    
    public init(frame: CGRect = .zero, closure: ((RisacTextFieldView, UITextField) -> Void)? = nil) {
        super.init(frame: frame)
        textField.delegate = self
        textField.addTarget(self, action: #selector(self.textFieldEditChanged(_:)), for: .editingChanged)
        self.addSubview(textField)
        closure?(self, textField)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func focus() {
        textField.becomeFirstResponder()
    }
    
    public func blur() {
        textField.resignFirstResponder()
    }
    
    private func updateInset() {
        textField.snp.remakeConstraints { (make) in
            make.edges.equalTo(contentInset)
        }
    }
}

extension RisacTextFieldView: UITextFieldDelegate {
    
    @objc func textFieldEditChanged(_ textField: UITextField) {
        if let selectedRange = textField.markedTextRange {
            if textField.position(from: selectedRange.start, offset: 0) != nil {
                return
            }
        }
        delegate?.textFieldEditChanged?(view: self, textField: textField)
    }
    
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return true
    }
    
    public func textFieldDidBeginEditing(_ textField: UITextField) {
        delegate?.textFieldEditBegin?(view: self, textField: textField)
    }
    
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.text = textField.text?.trim
        delegate?.textFieldReturn?(view: self, textField: textField)
        return true
    }
    
    public func textFieldDidEndEditing(_ textField: UITextField) {
        textField.text = textField.text?.trim
        delegate?.textFieldEditEnd?(view: self, textField: textField)
    }
}
